from scxml.pyscxml import StateMachine
import os
import logging
import uploadfile
import sys
import commonoperator
from executer import common

def ScxmlExcuter(queue, uploadconfig, templateid, taskid, subid, runpath, info, args):
    os.chdir(runpath)
    
    logging.basicConfig(filename = 'task.log', 
                                format='%(asctime)s %(levelname)-8s %(message)s',
                                datefmt='%Y%b%d %H:%M:%S',
                                level = logging.DEBUG)
    
    logging.info('task script begin run')
    logging.info(uploadconfig.ip)
    logging.info(uploadconfig.port)
    logging.info(str(info))
    
    info_for_caller = {}
    
    if args != None:
        sys.argv.extend(args.split())
    logging.info(str(sys.argv))
    
    uploadfiles = []
    uploadcasefiles = []
    
    try:
        sm = StateMachine(info['xml'])
        sm.start()
        
        if sm.datamodel['result'] == True:
            info_for_caller['result'] = common.SUCCESS
        else:
            info_for_caller['result'] = common.ERROR
        
        
        if commonoperator.case_result_file != None:
            uploadcasefiles.append(commonoperator.case_result_file)
    except SystemExit:
        logging.warn('script should`t have system exit')
        info_for_caller['result'] = common.EXCEPTION
        info_for_caller['message'] = 'scxml should`t have system exit exception'
    except Exception as e:
        logging.exception(e)
        info_for_caller['result'] = common.EXCEPTION
        info_for_caller['message'] = str(e)
    
    try:
        uploadfiles.append('task.log')
        uploadfile.UploadFile(uploadconfig, templateid, taskid, subid, uploadfiles, uploadcasefiles)
    except Exception as e:
        logging.exception(e)
    queue.put(info_for_caller)
